/***************************************************************************
 *   Copyright (C) 2008 by BogDan Vatra                                    *
 *   bogdan@licentia.eu                                                    *
 *                                                                         *
 *   This program is free software: you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation, either version 3 of the License, or     *
 *   (at your option) any later version.                                   *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>. *
 ***************************************************************************/

#include "query.h"
#include "database.h"

namespace SQL
{

Database * defaultDatabase(Database * database)
{
	static Database * d=0;
	if (database)
		d=database;
	if (!d)
		d = new Database();
	return d;
}

Database::Database(QObject *parent)
		: QObject(parent)
{
}

QSqlDatabase Database::database(const QString & connectionName, bool open)
{
	return QSqlDatabase::database(connectionName, open);
}

QSqlDatabase Database::addDatabase(const QString & type, const QString & connectionName)
{
	return QSqlDatabase::addDatabase(type, connectionName);
}

Query * Database::query(const QString & name)
{
	return findChild<Query*>(name);
}

void Database::bindGlobals(QSqlQuery * qry)
{
	QStringList placeholders=placeHolders(qry->lastQuery());
	foreach(QString placeholder, m_globalBindValues.keys())
	{
		QVariant val=m_globalBindValues[placeholder];
		if (!placeholder.startsWith(":"))
			placeholder = ":" + placeholder;
		if (placeholders.contains(placeholder))
			qry->bindValue(placeholder, val);
	}
}

void Database::bindValue(const QString & placeholder, const QVariant & val)
{
	m_globalBindValues[placeholder] = val;
}

QVariant Database::boundValue(const QString & placeholder) const
{
	return m_globalBindValues[placeholder];
}

const QMap<QString, QVariant> & Database::boundValues() const
{
	return m_globalBindValues;
}

QStringList Database::placeHolders(QString sql)
{
	QStringList placeholders;
	QRegExp rx(":([A-Za-z0-9_]+)");
	int pos = 0;
	sql.replace("::"," ");

	while ((pos = rx.indexIn(sql, pos)) != -1) 
	{
		placeholders << (":"+rx.cap(1));
		pos += rx.matchedLength();
	}
	
	return placeholders;
}

Database::~Database()
{
}

}
